﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace B.MESUI.Login.A_Public
{
    public partial class EncoderListForm : DevExpress.XtraEditors.XtraForm
    {
        private CodeGenApiClient _apiClient = new CodeGenApiClient();
        public event Action<string> RuleEditRequested;

        public EncoderListForm(string currentRuleName)
        {
            InitializeComponent();
            this.Load += EncoderListForm_Load;
        }

        private async void EncoderListForm_Load(object sender, EventArgs e)
        {
            var rules = await _apiClient.GetAllRules();
            gridControl1.DataSource = rules.Select(r => new {
                规则名 = r.ruleName,
                前缀 = r.prefix,
                连接符 = r.connector,
                流水号长度 = r.serialLength
            }).ToList();
            gridView1.PopulateColumns();
            AddOperationColumn();
        }

        private void AddOperationColumn()
        {
            if (gridView1.Columns["操作"] == null)
            {
                var col = gridView1.Columns.AddVisible("操作", "操作");
                col.UnboundType = DevExpress.Data.UnboundColumnType.String;
                col.ShowButtonMode = DevExpress.XtraGrid.Views.Base.ShowButtonModeEnum.ShowAlways;

                RepositoryItemButtonEdit buttonEdit = new RepositoryItemButtonEdit();
                buttonEdit.Buttons.Clear();
                buttonEdit.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph) { Caption = "删除" });
                buttonEdit.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph) { Caption = "修改" });
                buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                buttonEdit.ButtonClick += ButtonEdit_ButtonClick;
                col.ColumnEdit = buttonEdit;
            }
        }

        private void ButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var view = gridView1;
            var row = view.GetFocusedRow();
            if (row == null) return;

            string ruleName = (string)view.GetRowCellValue(view.FocusedRowHandle, "规则名");
            if (e.Button.Caption == "删除")
            {
                // 你可以扩展API支持删除规则，然后调用API删除
                XtraMessageBox.Show("请实现后端删除规则API并在此调用", "提示");
            }
            else if (e.Button.Caption == "修改")
            {
                RuleEditRequested?.Invoke(ruleName);
                this.Close();
            }
        }
    }
}